import datetime
import logging

from django.db.models.signals import post_save, post_init, post_delete
from django.dispatch import receiver

from finance.api.utils import create_journal, get_account, remove_journal
from finance.models import FundBill, RepaymentBill, Prepayment
from points.api.utils import PointDB

logger = logging.getLogger("django")


# 资金账单保存
@receiver(post_save, sender=FundBill)
def handle_bill_journal(sender, instance, created, **kwargs):
    logger.info('handle_bill_journal')

    source = ""
    if instance.category == 0:      # 费用
        source = '费用单付款'
    elif instance.category == 1:    # 收入
        source = '收入单收款'
    elif instance.category == 2:    # 借入
        source = '资金借入'
    elif instance.category == 3:    # 借出
        source = '资金借出'

    account = get_account(instance.account_id)
    if instance.verify == 1:
        data = {
            'order_no': instance.order_no,
            'name': instance.employee.name,
            'order_time': datetime.datetime.now(),
            'account': instance.account or None,
            'source': source,
            'money': instance.money if instance.category in [1, 2] else instance.money * -1,
            'balance': account.balance,
            'user': instance.user or None,
            'desc': instance.desc,
            'created': created,
        }
        logger.info(data)
        # 流水账记录
        create_journal(**data)


# 借入借出单删除
@receiver(post_delete, sender=FundBill)
def handle_bill_remove_journal(sender, instance, **kwargs):
    logger.info('handle_bill_remove_journal')
    remove_journal(instance.order_no)


# 还款记录
@receiver(post_save, sender=RepaymentBill)
def repayment_bill_journal(sender, instance, created, **kwargs):
    logger.info('repayment_bill_journal')

    source = ""
    if instance.bill.category == 2:    # 借入
        source = '资金借入还款'
    elif instance.bill.category == 3:    # 借出
        source = '资金借出还款'

    account = get_account(instance.bill.account_id)

    data = {
        'order_no': instance.order_no,
        'name': instance.bill.employee.name if instance.bill.employee else "",
        'order_time': datetime.datetime.now(),
        'account': instance.bill.account or None,
        'source': source,
        'money': instance.money * -1 if instance.bill.category == 2 else instance.money,
        'balance': account.balance,
        'user': instance.user or None,
        'desc': instance.desc,
        'created': created
    }
    logger.info(data)
    # 流水账记录
    create_journal(**data)


# 还款记录删除
@receiver(post_delete, sender=RepaymentBill)
def repayment_bill_remove_journal(sender, instance, **kwargs):
    logger.info('repayment_bill_remove_journal')
    remove_journal(instance.order_no)


# 预收款保存
@receiver(post_save, sender=Prepayment)
def handle_prepay_journal(sender, instance, created, **kwargs):
    logger.info('handle_prepay_journal')

    account = get_account(instance.account_id)
    if instance.flag == 0:
        data = {
            'order_no': instance.code,
            'name': instance.customer.name,
            'order_time': datetime.datetime.now(),
            'account': instance.account or None,
            'source': '客户预收款',
            'money': instance.amount,
            'balance': account.balance,
            'user': instance.oper_user or None,
            'desc': instance.remark,
            'created': created,
        }
        logger.info(data)
        # 流水账记录
        create_journal(**data)

        consume_data = {
            'code': instance.code,
            'customer': instance.customer or None,
            'category': 2,  # 消费积分
            'point': instance.amount,
            'user': instance.oper_user or None,
        }

        pointdb = PointDB()
        pointdb.create(**consume_data)


# 预收款删除
@receiver(post_delete, sender=Prepayment)
def handle_prepay_remove_journal(sender, instance, **kwargs):
    logger.info('handle_prepay_remove_journal')
    remove_journal(instance.code)

    pointdb = PointDB()
    pointdb.remove(instance.code)
